<template>

    <div>
        <Header></Header>
        <common-header>
            <template v-slot:title>
                我的购物车
            </template>
        </common-header>
        <el-divider></el-divider>
        <div>
            <el-row>
                <el-col :span="18" :offset="3">
                    <span class="all-goods">全部商品: {{carts.length}}</span>
                </el-col>
                <el-col :span="18" :offset="3">
                    <el-table
                        :data="carts"
                        style="width: 100%"
                        @selection-change="handleSelectionChange">
                        <el-table-column 
                            width="80" 
                            type="selection" 
                            @selection-change="handleSelectionChange" 
                            label="全选">
                        </el-table-column>
                        <el-table-column label="商品">
                            <template slot-scope="scope">
                                <div class="item">
                                    <el-image class="item-pic" :src="scope.row.pic"></el-image>
                                    <p class="item-title">
                                        {{scope.row.title}}
                                    </p>
                                </div> 
                            </template>
                        </el-table-column>
                        <el-table-column label="单价" prop="price" width="120"></el-table-column>
                        <el-table-column label="数量" prop="num">
                            <template slot-scope="scope">
                                <el-button type="info" size="mini" @click="minusNum(scope.row.id)" style="margin-right: 3px;">
                                    <i class="fa fa-minus"></i>
                                </el-button>
                                <el-input size="small" style="width: 80px;" v-model="scope.row.num" @focus="storeNum(scope.row.id, scope.row.num)" @blur="validateNum(scope.row.id)"></el-input> 
                                <el-button style="margin-left: 3px;" @click="addNum(scope.row.id)"  type="info" size="mini">
                                    <i class="fa fa-plus"></i>
                                </el-button>
                            </template>
                        </el-table-column>
                        <el-table-column label="小计">
                            <template slot-scope="scope">
                                <span style="font-weight: 600">
                                        ￥{{scope.row.price * scope.row.num}}
                                </span> 
                            </template> 
                        </el-table-column>
                        <el-table-column label="操作">
                            <template slot-scope="scope">
                                <el-button type="text" @click="deleteCart(scope.row.id)">删除</el-button>
                            </template>
                        </el-table-column>
                    </el-table>
                    <el-card style="margin-top: 10px;">
                        <div >
                            
                            <el-button type="text" style="margin-left: 10px;" @click="deleteAll">删除选中的商品</el-button>
                            
                                 <el-button type="danger" style="float: right;" @click.stop="skipSettle">去结算</el-button>
                            
                            <p style="float: right; margin-right: 10px;">
                                已选择 <span style="color: #e2231a; font-weight: 600;">{{checkedNum}}</span> 件商品
                                总价: <span style="color: #e2231a; font-weight: 600;">￥{{checkedPrice}}</span>
                            </p>
                        </div>
                    </el-card>
                </el-col>
            </el-row> 
        </div> 
    </div>
</template>

<script>
// import axios from 'axios'
import http from "../core/HttpRequest"
import CommonHeader from '../components/CommonHeader.vue'
import Header from '@/components/Index/Header'
export default {
    components: {
        CommonHeader,
        Header
    },
    data: () => ({
        checkAll: false,
        carts: [],
        deleteCarts: '',
        goodSimpleInfo: 0,
        checkedNum: 0,
        checkedPrice: 0,
        checkedId: new Array,
    }),
    mounted: function(){
        http.get('/shoppingCart/findAll',{
			params: {
				userName: this.$cookies.get("username")
			}
		}).then(res => {
           let data=res.data
            this.carts = data.data
        })
    },
    methods: {
        addNum(cId){
            const loading = this.$loading({
                lock: true,
                text: 'Loading',
                spinner: 'el-icon-loading',
                background: 'rgba(0, 0, 0, 0.7)'
            });
            
            // console.log(cId)
            console.log(cId)
            http.get("/shoppingCart/addNum",{
                params: {
                    shoppingCartId: cId
                }
            }).then(res => {
                console.log(res.data.message)
                if(res.data.message == "success"){
                    let c = this.carts.find(c => c.id == cId)
                    c.num++
                    this.$message({
                        showClose: true,
                        message: '添加成功',
                        type: 'success'
                    });
                    if(this.checkedId.indexOf(cId) != -1){
                        this.checkedNum++
                        this.checkedPrice+=c.price
                    }        
                }else{
                    this.$message.error('添加失误');
                }
                setTimeout(() => {
                    loading.close();
                });
            })
            
        },
        minusNum(cId){
            const loading = this.$loading({
                lock: true,
                text: 'Loading',
                spinner: 'el-icon-loading',
                background: 'rgba(0, 0, 0, 0.7)'
            });
            
            http.get("/shoppingCart/minusNum",{
                params: {
                    shoppingCartId: cId
                }
            }).then(res => {
                console.log(res.data.message)
                if(res.data.message == "success"){
                    let c = this.carts.find(c => c.id == cId) 
                    if(c.num == 1) {
                        // confirm() 用户点击 “确定” 返回true, 点击 “取消” 返回 false
                        if(confirm('目前数量为1, 你确定要删除该商品吗?')) {
                            let index = this.carts.indexOf(c)  // 获取到该商品所在的索引
                            this.carts.splice(index, 1)
                            return
                        }
                    }else {
                        if(this.checkedId.indexOf(cId) != -1){
                            this.checkedNum--
                            this.checkedPrice-=c.price
                        }   
                        c.num--
                        this.$message({
                            showClose: true,
                            message: '减少成功',
                            type: 'success'
                        });
                    }

                }else{
                    this.$message.error('减少失误');
                }
                setTimeout(() => {
                    loading.close();
                });
            })
            
        },
        deleteCart(cId){
            const loading = this.$loading({
                lock: true,
                text: 'Loading',
                spinner: 'el-icon-loading',
                background: 'rgba(0, 0, 0, 0.7)'
            });
            let c = this.carts.find(c => c.id == cId)
            if(confirm('你确定要删除该商品吗?')) {
                let index = this.carts.indexOf(c)  // 获取到该商品所在的索引
                this.carts.splice(index, 1)
                http.get("/shoppingCart/deleteCart",{
                    params: {
                        shoppingCartId: cId
                    }
                }).then(res => {
                    if(res.data.message == "success"){
                        this.$message({
                            showClose: true,
                            message: '删除成功',
                            type: 'success'
                        })
                    }else{
                        this.$message.error('删除失误')
                    }
                    setTimeout(() => {
                        loading.close();
                    });
                })
                return
            }
        },
        // 用户每次获得焦点，就将其原本的数量进行存储，以便于将来用户输入非数字的时候进行还原
        storeNum(cId, cNum) {
            this.goodSimpleInfo = {id: cId, num: cNum}
        },
        // 校验数据量
        validateNum(cId) {
            const loading = this.$loading({
                lock: true,
                text: 'Loading',
                spinner: 'el-icon-loading',
                background: 'rgba(0, 0, 0, 0.7)'
            });
            // 获取到用户当前的输入
            let c = this.carts.find(c => c.id == cId)
            
            let num = parseInt(c.num)
            let reg = /^[1-9]\d*$/;  // 以1-9开头
            if(!reg.test(num)) {// 不为数字
                c.num = this.goodSimpleInfo.num  // 就还原会以前的值
                loading.close();
            } else {
			
                http.get("/shoppingCart/assignNum",{
                    params: {
                        shoppingCartId: cId,
                        changeNum: num
                    }
                }).then(res => {
                        console.log(res.data.message)
                        if(res.data.message == "success"){
                            c.num = parseInt(c.num)
                            if(this.checkedId.indexOf(cId) != -1){
                                this.checkedNum += (c.num - this.goodSimpleInfo.num) 
                                this.checkedPrice += c.price * (c.num - this.goodSimpleInfo.num)
                            } 
                            
                            this.$message({
                                showClose: true,
                                message: '更改成功',
                                type: 'success'
                            });
                                
                        }else{
                            this.$message.error('更改失误');
                        }
                        setTimeout(() => {
                            loading.close();
                        });
                    })
                }
        },
        // 选中所有
        changeCheckAll(val) {
            this.checkedNum = 0
            this.checkedPrice = 0
            // window.console.log(val)
            this.deleteCarts = val
            for(let temp in val){
                window.console.log(temp)
                this.checkedNum += parseInt(temp.num)
                this.checkedPrice += parseInt(temp.price)*parseInt(temp.num)
                // console.log(temp.price*temp.num)
            }

        },
        deleteAll(){
            const loading = this.$loading({
                lock: true,
                text: 'Loading',
                spinner: 'el-icon-loading',
                background: 'rgba(0, 0, 0, 0.7)'
            });
            if(this.checkedId.length == 0){
                alert("您还未选择商品")
                loading.close();
            } else {
                if(confirm('你确定要删除选中商品吗?')) {
                for(let cart in this.deleteCarts){
                    let c = this.carts.find(c => c.id == cart.id)
                    
                    let index = this.carts.indexOf(c)  // 获取到该商品所在的索引
                    this.carts.splice(index, 1)
                        
                    
                }
                let address = new URLSearchParams()
                address.append('checkedShoppingCartId', this.checkedId), 
                 
                http({
                    method: "post",
                    url: `/shoppingCart/deleteCheckedCart`,
                    data: address
                }).then(res => {
                    if(res.data.message == "success"){
                        this.$message({
                            showClose: true,
                            message: '删除成功',
                            type: 'success'
                        })
                    }else{
                        this.$message.error('删除失误')
                    }
                    setTimeout(() => {
                        loading.close();
                    });
                })
            }
            }
            
        },
        // 勾选某件商品val
        handleSelectionChange(val) {
            this.checkedNum = 0
            this.checkedPrice = 0
            this.checkedId = new Array;
            // window.console.log(val)
            this.deleteCarts = val
            for(let temp in val){
                // window.console.log(temp)
                let c = this.carts.find(c => c.id == val[temp].id)
                this.checkedNum += c.num
                this.checkedPrice += c.price * c.num
                this.checkedId.push(c.id)
            }
            
        },
        skipSettle(){
            // console.log(this.checkedId)
            if(this.checkedId.length == 0){
                alert("您还没有选择宝贝哟！")
                return
            } else {
                this.$cookies.set("shoppingCartId",this.checkedId)
                this.$router.push({
                    path: 'settle',
                    query: {
                        
                    }
                }); 
                  
            }
            
            
            
        }
    }
}
</script>

<style scoped>
    .item {
        display: flex;
    }
    .item .item-pic {
        width: 60px;
        height: 60px;
    }
   
    .item .item-title {
        padding-left: 8px; 
        width: 180px;
    }
    .settle-panel {
        position: fixed;
        width: 100%;
        bottom: 0;
        z-index: 1000;
    }
     .settle-panel .checkall-btn {
         position:absolute;
         top: 8px;
     }
    .settle-panel .del-all {
        position:absolute;
        left: 70px;
        top: 10px;
    }
    .settle-panel .settle-btn {
        position:absolute;
        top: -5px;
        right: 100px;
    }
    .all-goods {
        color: #F56C6C; 
        font-weight: 600; 
        font-size: 18px;
    }
</style>